import { createRouter, createWebHashHistory } from 'vue-router'
import { routes } from 'vue-router/auto-routes'

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        ...routes,
        {
            path: '/:pathMatch(.*)*',
            redirect: '/404'
        }
    ]
})

const whileList = [
    '/login',
    '/register',
    '/404',
    '/403'
]

const tokenValid = () => {
    const token = localStorage.getItem('token')
    const expiresIn = localStorage.getItem('expiresIn')
    if (!token || !expiresIn) {
        return false
    }
    if (Date.now() > expiresIn) {
        return false
    }
    return true
}

router.beforeEach((to, from, next) => {
    if (whileList.includes(to.path)) {
        next()
    } else {
        const valid = tokenValid()
        if (valid) {
            next()
        } else {
            next('/login')
        }
    }
})


export default router
